<!DOCTYPE html>
<html >
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    
    <title>采用正则解析协议 | xilixili.net</title>
    <meta name="renderer" content="webkit">
    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="description" content="大家都知道开发网络协议的C++一般是很少的，比如HTTP、RTSP、SIP等就很少，如果有特殊需求基本上已经没有什么可以使用的库了，所以C++程序员一般热衷于造轮子。记得之前做异步HTTP的时候，基本都是ASIO做网络I/O，数据自己来做解析，各种的匹配，逐条处理等等。
比如在解析HTTP文本的时候，基本就是先找CRLF，取出单条，然后再找分割符，然后再取值前后TRIM等，写起来相当的不方便，参考">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="采用正则解析协议 | xilixili.net">
    <meta name="twitter:description" content="大家都知道开发网络协议的C++一般是很少的，比如HTTP、RTSP、SIP等就很少，如果有特殊需求基本上已经没有什么可以使用的库了，所以C++程序员一般热衷于造轮子。记得之前做异步HTTP的时候，基本都是ASIO做网络I/O，数据自己来做解析，各种的匹配，逐条处理等等。
比如在解析HTTP文本的时候，基本就是先找CRLF，取出单条，然后再找分割符，然后再取值前后TRIM等，写起来相当的不方便，参考">

    <meta property="og:type" content="article">
    <meta property="og:title" content="采用正则解析协议 | xilixili.net">
    <meta property="og:description" content="大家都知道开发网络协议的C++一般是很少的，比如HTTP、RTSP、SIP等就很少，如果有特殊需求基本上已经没有什么可以使用的库了，所以C++程序员一般热衷于造轮子。记得之前做异步HTTP的时候，基本都是ASIO做网络I/O，数据自己来做解析，各种的匹配，逐条处理等等。
比如在解析HTTP文本的时候，基本就是先找CRLF，取出单条，然后再找分割符，然后再取值前后TRIM等，写起来相当的不方便，参考">

    
    <meta name="author" content="rangerlee">
    
    <link rel="stylesheet" href="/css/vno.css">
    <link rel="stylesheet" href="/css/font-awesome.min.css">

    
    <link rel="icon" href="/images/avatar-small.png">
    

    <meta name="generator" content="hexo"/>
    
    <link rel="alternate" type="application/rss+xml" title="xilixili.net" href="/atom.xml">
    

    <link rel="canonical" href="xilixili.net/2018/03/05/parse-protocol-with-regex/"/>

                 
</head>

<body class="home-template no-js">
    <script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script src="/js/main.js"></script>
    <span class="mobile btn-mobile-menu">
        <i class="fa fa-list btn-mobile-menu__icon"></i>
        <i class="fa fa-angle-up btn-mobile-close__icon hidden"></i>
    </span>

    
<header class="panel-cover panel-cover--collapsed">
  <div class="panel-main">
    <div class="panel-main__inner panel-inverted">
    <div class="panel-main__content">

        <h1 class="panel-cover__title panel-title"><a href="/" title="访问首页 xilixili.net">xilixili.net</a></h1>
        
        <span class="panel-cover__subtitle panel-subtitle"><!-- 生活と技术の杂记 --></span>
        
        <hr class="panel-cover__divider">
        
        <p class="panel-cover__description">生活と技术の杂记</p>
        
	<hr class="panel-cover__divider panel-cover__divider--secondary">

        <div class="navigation-wrapper">
          <div>
          <nav class="cover-navigation cover-navigation--primary">
            <ul class="navigation">
              <li class="navigation__item"><a href="/#blog" title="访问博客" class="blog-button">博客</a></li>
            
            </ul>
          </nav>
          </div>
          <div>
          <nav class="cover-navigation navigation--social">
  <ul class="navigation">

  <!-- Weibo-->
  

  <!-- Github -->
  
  <li class="navigation__item">
    <a href="https://github.com/rangerlee" title="查看我的GitHub主页" target="_blank">
      <i class="social fa fa-github"></i>
      <span class="label">Github</span>
    </a>
  </li>


<!-- Stack Overflow -->
        

  <!-- Google Plus -->
  

<!-- Facebook -->

  
<!-- Twitter -->

  

  <li class="navigation__item">
    <a href="/atom.xml" title="RSS" target="_blank">
      <i class="social fa fa-rss"></i>
      <span class="label">RSS</span>
    </a>
  </li>


  <li class="navigation__item">
    <a href="mailto:http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&amp;email=RzUmKSAiNSsiIgchKD8qJi4raSQoKg" title="邮件联系我" target="_blank">
      <i class="social fa fa-envelope"></i>
      <span class="label">Email</span>
    </a>
  </li>


  </ul>
</nav>

          </div>
        </div>

      </div>

    </div>

    <div class="panel-cover--overlay cover-alpha"></div>
  </div> 
</header>
<script type="text/javascript">
var side = document.getElementsByClassName("panel-cover")[0];
function checkWebp() {
	try{
		return(document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0);
	}catch(err) {
		return false;
	}
};

if(checkWebp()) {
	side.style.backgroundImage = "url('/images/background-cover.jpg.webp')";
} else {
	side.style.backgroundImage = "url('/images/background-cover.jpg')";
}
</script>


    <div class="content-wrapper">
        <div class="content-wrapper__inner">
            <article class="post-container post-container--single">

  <header class="post-header">
    <div class="post-meta">
      <time datetime="2018-03-05T09:43:00.000Z" class="post-list__meta--date date">2018-03-05</time> &#8226; <span class="post-meta__tags tags">
  <a class="tag-link" href="/tags/技术/">技术</a>
 </span>
      <span class="page-pv">
       阅读 <span id="busuanzi_value_page_pv"><i class="fa fa-spinner fa-spin"></i></span>
      </span> 
   
    </div>
    <h1 class="post-title">采用正则解析协议</h1>
  </header>

  <section class="post">
    <p>大家都知道开发网络协议的C++一般是很少的，比如HTTP、RTSP、SIP等就很少，如果有特殊需求基本上已经没有什么可以使用的库了，所以C++程序员一般热衷于造轮子。记得之前做异步HTTP的时候，基本都是ASIO做网络I/O，数据自己来做解析，各种的匹配，逐条处理等等。</p>
<p>比如在解析HTTP文本的时候，基本就是先找CRLF，取出单条，然后再找分割符，然后再取值前后TRIM等，写起来相当的不方便，参考网上其他人的解析基本还是一个字节一个字节的往后偏移查找，效率就更慢了，也很难支持异步数据处理。</p>
<p>最近想调测下RTSP协议的推流等，主要还是要解析RTSP协议，live555不好用，而且网络模型不太合适，打算自己写个新的通信框架。在GITHUB上搜索了下，也没什么合适的解析库，还好RTSP协议也是文本方式的请求响应模式，大概如下</p>
<figure class="highlight http"><table><tr><td class="code"><pre><span class="line">OPTIONS rtsp://xxx.xxx.xxx.xxx:554/tcp.sdp RTSP/1.0</span><br><span class="line"><span class="attribute">CSeq</span>: 1</span><br><span class="line"><span class="attribute">User-Agent</span>: Lavf56.23.105</span><br><span class="line"></span><br><span class="line">RTSP/1.0 200 OK</span><br><span class="line"><span class="attribute">Server</span>: DSS/7.0.0 (Build/15.0310; Release/EasyDarwin; State/Development; )</span><br><span class="line"><span class="attribute">Cseq</span>: 1</span><br><span class="line"><span class="attribute">Public</span>: DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE, OPTIONS, ANNOUNCE, RECORD</span><br></pre></td></tr></table></figure>
<p>其实都是有固定格式的，不由得的想到了正则表达式，觉得很多匹配应该交由正则来实现，比如解析请求的时候，基本上就是首行+头域+负载三部分构成。首行和头域都是以换行(CRLF)分割的，我们只需要解析出一行行的字符串，然后去正则匹配就可以取出想要的Token了。比如首行取出请求命令和URI的代码如下</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="built_in">std</span>::<span class="built_in">string</span> line = <span class="string">"PLAY rtsp://xx.a.a/xxxx/aa?dd=22 RTSP/1.0"</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="built_in">std</span>::<span class="function">regex <span class="title">pattern</span><span class="params">(<span class="string">"(\\w&#123;4,&#125;)\\s(\\S&#123;1,&#125;)\\sRTSP\\/1.0"</span>)</span></span>;</span><br><span class="line"><span class="built_in">std</span>::match_results&lt;<span class="built_in">std</span>::<span class="built_in">string</span>::const_iterator&gt; result;</span><br><span class="line"><span class="keyword">bool</span> valid = <span class="built_in">std</span>::regex_match(line, result, pattern);</span><br><span class="line"><span class="keyword">if</span>(valid)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">puts</span>(result[<span class="number">1</span>].str().c_str());	</span><br><span class="line">	<span class="built_in">puts</span>(result[<span class="number">2</span>].str().c_str());	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>就会取出 <code>PLAY</code> 和 <code>rtsp://xx.a.a/xxxx/aa?dd=22</code>, 非常方便。再如头域的K/V提取</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="built_in">std</span>::<span class="built_in">string</span> line = <span class="string">"Test-Key: DDD ddd \"dd\", xx=aaa ()001///dd"</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="built_in">std</span>::<span class="function">regex <span class="title">pattern</span><span class="params">(<span class="string">"(\\w&#123;1,&#125;):\\s*([^\f\n\r\t\v]+)"</span>)</span></span>;</span><br><span class="line"><span class="built_in">std</span>::match_results&lt;<span class="built_in">std</span>::<span class="built_in">string</span>::const_iterator&gt; result;</span><br><span class="line"><span class="keyword">bool</span> valid = <span class="built_in">std</span>::regex_match(line, result, pattern);</span><br><span class="line"><span class="keyword">if</span>(valid)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">puts</span>(result[<span class="number">1</span>].str().c_str());	</span><br><span class="line">	<span class="built_in">puts</span>(result[<span class="number">2</span>].str().c_str());	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以取出 <code>Test-Key</code> 和 <code>DDD ddd &quot;dd&quot;, xx=aaa ()001///dd</code>, 这样整个消息解析起来就会非常方便。</p>

  </section>

</article>

<section class="read-more">
           
    
               
            <div class="read-more-item">
                <span class="read-more-item-dim">最近的文章</span>
                <h2 class="post-list__post-title post-title"><a href="/2018/03/07/cpp-format-library/" title="C++字符串格式化库">C++字符串格式化库</a></h2>
                <p class="excerpt">
                
                总的来说，C++可使用的字符串格式化库是非常少，基本可选用的如sprintf系列，boost.format等，诚然stringstream也可以，但是和其他库有明显使用上的区别，不是很方便。
自实现的格式化库曾经因为项目日志打印问题，比如申请多少缓冲区问题，为了防止越界等问题，多方考虑自己实现了一个
                &hellip;
                </p>
                <div class="post-list__meta"><time datetime="2018-03-07T09:00:00.000Z" class="post-list__meta--date date">2018-03-07</time> &#8226; <span class="post-list__meta--tags tags">
  <a class="tag-link" href="/tags/技术/">技术</a>
</span><a class="btn-border-small" href="/2018/03/07/cpp-format-library/">继续阅读</a></div>
                           
            </div>
        
        
               
            <div class="read-more-item">
                <span class="read-more-item-dim">更早的文章</span>
                <h2 class="post-list__post-title post-title"><a href="/2018/02/26/webrtc-with-28181-live/" title="通过28181与WebRTC直播摄像头">通过28181与WebRTC直播摄像头</a></h2>
                <p class="excerpt">
                
                前文描述了WebRTC视频直播技术，后续应用到系统中，版本已经做出来了并封装了JS的SDK，实时性效果还是非常令人惊喜的，针对部分调整和问题进行记录。
视频源项目使用的是海康摄像头，我打算取消本地服务器，直接让摄像头通过GB28181协议进行推流。为了让所有用户可以观看，将服务部署在公网，当然这里需
                &hellip;
                </p>
                <div class="post-list__meta"><time datetime="2018-02-26T07:46:00.000Z" class="post-list__meta--date date">2018-02-26</time> &#8226; <span class="post-list__meta--tags tags">
  <a class="tag-link" href="/tags/技术/">技术</a>
</span><a class="btn-border-small" href="/2018/02/26/webrtc-with-28181-live/">继续阅读</a></div>
                       
            </div>
        
     
   
   
  
</section>



	<script>
	(function(){
		var bp = document.createElement('script');
		var curProtocol = window.location.protocol.split(':')[0];
		if (curProtocol === 'https') {
			bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
		}
		else {
			bp.src = 'http://push.zhanzhang.baidu.com/push.js';
		}
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(bp, s);
	})();
	</script>



<script>
(function(){
var src = (document.location.protocol == "http:") ? "http://js.passport.qihucdn.com/11.0.1.js?8612a7fa26d7ba4562be733ae33649b1":"https://jspassport.ssl.qhimg.com/11.0.1.js?8612a7fa26d7ba4562be733ae33649b1";
document.write('<script src="' + src + '" id="sozz"><\/script>');
})();
</script>



            <footer class="footer">
    <span class="footer__copyright">
        &copy; 2023 rangerlee - 本站点采用 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/">知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议</a>
       
    </span>
    <span class="footer__copyright">
             - 本站基于开源 <a href="http://hexo.io">Hexo</a> 搭建，采用 <a href="https://github.com/rangerlee/hexo-theme-new-vno">hexo-theme-new-vno</a> 主题，修改自 <a href="https://github.com/monniya/hexo-theme-new-vno ">new-vno</a> 主题  <a href="http://www.beian.miit.gov.cn">皖ICP备16009457号</a>
         </span>
       
    
    
</footer>


        </div>
    </div>

     
    
    <script>
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "//hm.baidu.com/hm.js?bab4f71524319c10819bcae280021624";
            var s = document.getElementsByTagName("script")[0]; 
            s.parentNode.insertBefore(hm, s);
        })();
    </script>



    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    
    
</body>
</html>
